﻿using System;
using System.Linq;
using System.Collections.Generic;
using Light.Framework.Model;
using Light.Framework.Castle;
using NHibernate.Criterion;
using Light.Framework.Contract;
using Castle.ActiveRecord;
using System.Security.Permissions;
using System.Text;
using System.Data;
using Light.Utility;
using System.Data.Common;

namespace Light.Framework.Component
{
    public class SysParameterComponent : ISysParameterComponent
    {
        #region ISysParameterComponent 成员

        public SysParameter Get(string key)
        {
            return ActiveRecordMediator<SysParameter>.FindByPrimaryKey(key);
        }

        public string GetValue(string key)
        {
            ICriterion criterion = Expression.Eq("Key", key);
            SysParameter model = ActiveRecordMediator<SysParameter>.FindFirst(criterion);
            if (model != null)
                return model.Value;
            return string.Empty;
        }

        public IList<SysParameter> Get()
        {
            return ActiveRecordMediator<SysParameter>.FindAll();
        }

        public OperateResult Save(string key, string value)
        {
            OperateResult result = new OperateResult();

            SysParameter model = new SysParameter { Key = key, Value = value };
            try
            {
                model.Save();

                result.IsSucced = true;
                result.Message = "保存成功！";
            }
            catch (Exception ex)
            {
                result.IsSucced = false;
                result.Message = "保存失败！" + ex.Message;
            }
            return result;
        }

        public OperateResult Save(params SysParameter[] models)
        {
            OperateResult result = new OperateResult();

            try
            {
                foreach (var model in models)
                {
                    model.Save();
                }
                result.IsSucced = true;
                result.Message = "保存成功！";
            }
            catch (Exception ex)
            {
                result.IsSucced = false;
                result.Message = "保存失败！" + ex.Message;
            }
            return result;
        }

        public OperateResult Delete(string key)
        {
            SysParameter model = Get(key);
            return Delete(model);
        }

        public OperateResult Delete(SysParameter model)
        {
            OperateResult result = new OperateResult();
            try
            {
                ActiveRecordMediator.DeleteAndFlush(model);

                result.IsSucced = true;
                result.Message = "删除成功！";
            }
            catch (Exception ex)
            {
                result.IsSucced = false;
                result.Message = "删除失败！" + ex.Message;
            }
            return result;
        }

        #endregion
    }
}
